<template>
    <Layout>
        <Row>
            <Card dis-hover >
                <h3>
                    {{taskInfo.taskName}}
                </h3>
                <ButtonGroup slot="extra"  v-if="!taskInfo.viewFlag">

                    <Button  @click="submitAndUpdate('showdata')" type="warning" style="background: #EF5350;" :loading="buttonloading1"  v-if="taskInfo.procinstState === '2'">
                        <Icon type="ios-bookmark" />
                        审批
                    </Button>
                    <Button  @click="submit('showdata')" type="warning" style="background: #EF5350;" :loading="buttonloading1" v-else>
                        <Icon type="ios-bookmark" />
                        审批
                    </Button>

                    <Button @click="returnTo">
                        返回
                        <Icon type="ios-arrow-forward" />
                    </Button>
                </ButtonGroup>
                <ButtonGroup slot="extra"  v-else>
                    <Button @click="returnTo">
                        返回
                        <Icon type="ios-arrow-forward" />
                    </Button>
                </ButtonGroup>

            </Card>

            <i-col>
                <Card dis-hover style="margin-top: 10px">
                    <div :style="{ overflowY: 'auto'}" v-if="taskInfo.procinstState === '2'"  >
                        <Col span="18">
                            <Form  :model="showdata"  ref="showdata" :rules="ruleCustom1" :label-width="160">
                                <Row type="flex" justify="space-around" class="code-row-bg">
                                    <Col span="11" >
                                        <FormItem label="审计任务：" prop="missionName">
                                            {{showdata.missionName}}
                                        </FormItem>
                                    </Col>
                                    <Col span="11">
                                        <FormItem label="组长：" prop="groupLeaderName">
                                            {{showdata.groupLeaderName}}
                                        </FormItem>
                                    </Col>

                                </Row>
                                <Row type="flex" justify="space-around" class="code-row-bg">
                                    <Col span="23" >
                                        <FormItem label="审计单位：" prop="auditedOrgName">
                                            {{showdata.auditedOrgName}}
                                        </FormItem>
                                    </Col>

                                </Row>
                                <Row type="flex" justify="space-around" class="code-row-bg">
                                    <Col span="11">
                                        <FormItem label="开始时间：" prop="planStart">
                                            {{formatDate(new Date(showdata.planStart), 'yyyy-MM-dd')}}
                                        </FormItem>
                                    </Col>
                                    <Col span="11" >
                                        <FormItem label="结束时间：" prop="whetherComments">
                                            {{formatDate(new Date(showdata.planEnd), 'yyyy-MM-dd')}}
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row type="flex" justify="space-around" class="code-row-bg">
                                    <Col span="11">
                                        <FormItem label="公司领导：" prop="projectManagerName">
                                            {{showdata.projectManagerName}}
                                        </FormItem>
                                    </Col>
                                    <Col span="11" >
                                        <FormItem label="集团领导：" prop="companyManagerName">
                                            {{showdata.companyManagerName}}
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row type="flex" justify="space-around" class="code-row-bg">
                                    <Col span="23" >
                                        <FormItem label="方案概述：" prop="programmeDesc">
                                            <Input v-model="showdata.programmeDesc" type="textarea" :rows="4" />
                                        </FormItem>
                                    </Col>
                                </Row>

                                <Row type="flex" justify="space-around" class="code-row-bg">
                                    <Col span="23">
                                        <FormItem label="整改方案附件：">
                                            <div>
                                                <Upload ref="upload"
                                                        :before-upload="beforeUpload"
                                                        :show-upload-list="true"
                                                        :max-size="10240"
                                                        multiple
                                                        type="drag"
                                                        :action="fileUrl">
                                                    <div style="padding: 10px">
                                                        <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                                                        <p>点击将文件拖拽到这里上传</p>
                                                        <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                                                    </div>
                                                </Upload>
                                            </div>
                                            <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                                                <a @click="downloadFile(form1datacopy.programmeId,item)">{{ item.fileName }}</a>
                                                <Button type="text" icon="md-trash" @click="remove1(item.id)"
                                                        style="margin-left: 5px;margin-bottom: 3px"/>
                                            </div>
                                        </FormItem>
                                    </Col>
                                </Row>

                            </Form>
                        </Col>
                    </div>
                    <div :style="{ overflowY: 'auto'}" v-else>
                        <Col span="24">
                            <Form  :model="showdata"  ref="showdata" :rules="ruleCustom" :label-width="160">
                                <Row type="flex" justify="space-around" class="code-row-bg">
                                    <Col span="11" >
                                        <FormItem label="审计任务：" prop="missionName">
                                            {{showdata.missionName}}
                                        </FormItem>
                                    </Col>
                                    <Col span="11">
                                        <FormItem label="组长：" prop="groupLeaderName">
                                            {{showdata.groupLeaderName}}
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row type="flex" justify="space-around" class="code-row-bg">
                                    <Col span="23" >
                                        <FormItem label="审计单位：" prop="auditedOrgName">
                                            {{showdata.auditedOrgName}}
                                        </FormItem>
                                    </Col>

                                </Row>
                                <Row type="flex" justify="space-around" class="code-row-bg">
                                    <Col span="11">
                                        <FormItem label="开始时间：" prop="planStart">
                                            {{formatDate(new Date(showdata.planStart), 'yyyy-MM-dd')}}
                                        </FormItem>
                                    </Col>
                                    <Col span="11" >
                                        <FormItem label="结束时间：" prop="whetherComments">
                                            {{formatDate(new Date(showdata.planEnd), 'yyyy-MM-dd')}}
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row type="flex" justify="space-around" class="code-row-bg">
                                    <Col span="11">
                                        <FormItem label="公司领导：" prop="projectManagerName">
                                            {{showdata.projectManagerName}}
                                        </FormItem>
                                    </Col>
                                    <Col span="11" >
                                        <FormItem label="集团领导：" prop="companyManagerName">
                                            {{showdata.companyManagerName}}
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row type="flex" justify="space-around" class="code-row-bg">
                                    <Col span="23">
                                        <FormItem label="方案概述：" prop="programmeDesc">
                                            {{showdata.programmeDesc}}
                                        </FormItem>
                                    </Col>
                                </Row>

                                <Row type="flex" justify="space-around" class="code-row-bg">
                                    <Col span="23">
                                        <FormItem label="整改方案附件：">
                                            <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                                                <a @click="downloadFile(showdata.programmeId,item)">{{ item.fileName }}</a>
                                            </div>
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row v-if="!taskInfo.viewFlag">
                                    <Col span="11">
                                        <FormItem label="审批结果：" prop="route">
                                            <Select  v-model="showdata.route"  @on-change="routePush">
                                                <Option v-for="item in approveList" :value="item.value" :key="item.value">{{ item.text }}</Option>
                                            </Select>
                                        </FormItem>
                                    </Col>

                                </Row>
                                <Row v-if="!taskInfo.viewFlag">
                                    <Col span="11">
                                        <FormItem label="处理意见：" prop="opinion">
                                            <Input v-model="showdata.opinion" type="textarea" :rows="2" />
                                        </FormItem>
                                    </Col>
                                </Row>

                            </Form>
                        </Col>
                    </div>
                </Card>
            </i-col>
        </Row>

        <Modal v-model="model2" :width=800 title="相关方台账">
            <Form ref="pageModel2" :model="pageModel2" :label-width="120">
                <Row class="query-form">
                    <Col span="8">
                        <FormItem label="企业名称：">
                            <Input type="text" v-model="pageModel2.contractorName"/>
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <Button @click="reset" class="ivu-btn-reset">重置</Button>
                        <Button class="ivu-btn-query" icon="md-search" @click="selectContractor()">查询</Button>
                    </Col>
                </Row>
                <Row>
                    <Col span="24">
                        <Table height="300" no-data-text="没有查询到相关数据！" @on-row-dblclick="danxuan"
                               highlight-row stripe border :columns="columns2" width="100%" :data="contractor">
                        </Table>
                    </Col>
                </Row>
                <Row style="margin-right:10px;">
                    <Col span="24">
                        <Page :total="pageModel2.total" :page-size="pageModel2.pageSize" @on-change="pageChange1"
                              style="float: right" @on-page-size-change="pageSizeChange1"
                              :page-size-opts="pageSizeArray"
                              show-total show-sizer show-elevator/>
                    </Col>
                </Row>
            </Form>
            <div slot="footer" style="padding: 1px 1px 1px 1px;">
                <!--<Button type="text" @click="model2=false,buttonDisabled=false">取消</Button>-->
                <!--<Button    :disabled="buttonDisabled" @click="baocun">确定</Button>-->
            </div>
        </Modal>
    </Layout>
</template>


<script>
    import {Api} from '../../../api/index.js'
    import { sessionStorage, cookie } from '../../../common/cacheUtils.js'
    import cascaderDom from "../../../components/cascader-dom.vue"
    export default {
        components: {
            cascaderDom
        },
        data() {
            return {
                user:{},
                taskInfo:{},
                buttonloading1:false,
                fileUrl: Api.interestedPartiesUserFile,
                pageModel2: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                    contractorName: ''
                },
                contractor: [],
                pageSizeArray: [10, 20, 50],
                columns2: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 100,
                        align: 'center',
                    },
                    {
                        minWidth: 150,
                        title: '企业名称',
                        align: 'center',
                        key: 'contractorName',
                    },
                    {
                        minWidth: 150,
                        title: '企业性质',
                        align: 'center',
                        key: 'propertyName',
                    },
                    {
                        minWidth: 150,
                        title: '法定代表人',
                        align: 'center',
                        key: 'legalPerson',
                    },
                    {
                        minWidth: 150,
                        title: '注册资本',
                        align: 'center',
                        key: 'capital',
                    },
                    {
                        minWidth: 150,
                        title: '统一社会信用代码',
                        align: 'center',
                        key: 'unifyCode',
                    },
                ],
                evaluationPeriodDate:[null,null],
                contractTermDate:[null,null],
                uploadList:[],
                evaluationPeriodDate1:null,
                contractTermDate1:null,
                viewFlag : false,
                flag : false,
                approveFlag : '',
                approveList : [
                    {
                        text:"通过",
                        value:"1"
                    },
                    {
                        text:"不通过",
                        value:"2"
                    }
                ],
                showdata: {},
                tableHeight : 450,
                file : null,
                fileName : null,
                downloadUrl : Api.downloadMongoFile,
                formList : [],
                ruleCustom1:{
                    serviceName: [{
                        message: '  ',
                        required: true,
                        trigger: 'blue'
                    }],
                    contacts: [{
                        message: '  ',
                        required: true,
                        trigger: 'blur'
                    }],
                    contractorName: [{
                        message: '  ',
                        required: true,
                        trigger: 'change'
                    }],
                    supplierQualification: [{
                        message: '  ',
                        required: true,
                        trigger: 'blur'
                    }],
                    contractTermDate: [{
                        validator: (rule, value, callback) => {
                            if (this.contractTermDate == null || this.contractTermDate[0] == null) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    phone: [{
                        validator: (rule, value, callback) => {
                            if(!(/^1[3456789]\d{9}$/.test(value))){
                                callback(' ');
                                this.$Message.error("请填写有效的的手机号")
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'blur'
                    }],
                    evaluationPeriodDate: [{
                        validator: (rule, value, callback) => {
                            if (this.evaluationPeriodDate == null || this.evaluationPeriodDate[0] == null) {
                                callback(' ')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                    managementEvaluation: [{
                        message: '  ',
                        required: true,
                        trigger: 'blur'
                    }],
                    performanceEvaluation: [{
                        message: '  ',
                        required: true,
                        trigger: 'blur'
                    }],
                    afterSaleEvaluation: [{
                        message: '  ',
                        required: true,
                        trigger: 'blur'
                    }],
                    comprehensiveEvaluation: [{
                        message: '  ',
                        required: true,
                        trigger: 'blur'
                    }],
                },
                ruleCustom : {
                    opinion: [
                        { required: true, message: '  ', trigger: 'blur' }
                    ],

                    route: [
                        { required: true, message: '  ', trigger: 'blur' }
                    ]
                }
            }
        },
        mounted: function() {
            this.tableHeight = window.innerHeight - 190;
            if(this.$route.query.close == false){
                this.$http.get(Api.getUserByUserId + this.$route.query.userId)
                .then(function(res){
                    this.user = res.data.data;
                    this.$http.get(Api.getTaskData + "/" + this.$route.query.procinstId + "/" +
                    this.$route.query.taskId+"?close="+this.$route.query.close).then(function(res1){
                        this.taskInfo = res1.data;
                        if(res1.data.viewFlag == false)
                            this.taskInfo.viewFlag = false;
                        else
                            this.taskInfo.viewFlag = true;
                        this.query();
                        return ;
                    })
                })
            }else{
                var search=window.location.href.split('?')[1];//截取URL？后面的参数
                var params={};
                if(search!=""&&search!=undefined){
                　　search.split("&").forEach(
                        function(val){
            　　　　        var arr=val.split("=");
            　　　　      params[arr[0]]=arr[1];
                        }
                    )}
                var code=params.code
                var status = params.status
                if(code != null && code != 'undefine'){
                    this.$http.get(Api.queryToken, {
                        params: {
                            code: code,
                        }
                    }).then(res1 => {
                        if(res1.data.errcode == "1014"){
                             this.$http.get(Api.getReZheng).then(res2=>{
                               window.location.href = decodeURIComponent(res2.bodyText) + "&redirect_uri="+encodeURIComponent(window.location.href);
                             })
                        }
                        else{
                            this.$http.get(Api.getUserByUserId + this.$route.query.userId)
                            .then(function(res){
                                this.user = res.data.data;
                                this.$http.get(Api.getTaskData + "/" + this.$route.query.procinstId + "/" +
                                this.$route.query.taskId+"?close="+this.$route.query.close).then(function(res1){
                                    this.taskInfo = res1.data;
                                    if(res1.data.viewFlag == false)
                                        this.taskInfo.viewFlag = false;
                                    else
                                        this.taskInfo.viewFlag = true;
                                    this.query();
                                    return ;
                                })
                            })
                        }
                    })
                }
                else{
                    this.$http.get(Api.getReZheng).then(res2=>{
                       window.location.href = decodeURIComponent(res2.bodyText) + "&redirect_uri="+encodeURIComponent(window.location.href);
                    });
                }
            }
        },
        methods: {
            returnTo(){
                if(this.taskInfo.close == true)
                    window.close();
                else
                   this.$router.go(-1);
            },
            routePush(value){
                if (value === '1') {
                    this.showdata.opinion = "同意";
                }else{
                    this.showdata.opinion = null;
                }
            },
            remove1(id) {
                let istrue = confirm("是否删除该文件？");
                if (istrue) {
                    let url = this.fileUrl + '/file/' + id;
                    this.$http.delete(url).then((res) => {
                        this.getFiles()
                    })
                }

            },

            beforeUpload(file) {
                let formData = new FormData();
                formData.append("files", file); // 文件对象
                let url = this.fileUrl + '/' + this.showdata.programmeId + '/files/adtProgramme'
                this.$http.post(url, formData).then((res) => {
                    if (res.data.result == "success") {
                        this.$Message.info("文件上传成功")
                        this.getFiles();
                    }
                })
                return false
            },
            getFiles() {
                let url = this.fileUrl + '/' + this.showdata.programmeId + '/files/adtProgramme'
                this.$http.get(url).then((res) => {
                    if (res.data.result == "success") {
                        this.uploadList = res.data.data
                        console.log(this.uploadList);
                    }
                })
            },
            setApproveUserName(data) {
                this.showdata.approveUserName = data;
            },
            setApproveUserId(data) {
                this.showdata.approveUserId = data[data.length - 1];
            },

            setApproveUserName1(data) {
                this.showdata.approveUserName = data;
            },
            setApproveUserId1(data) {
                let userId = "";
                for(let i=0;i<data.length;i++){
                    userId += data[i]['value'] + ',';
                }
                this.showdata.approveUserId = userId;
            },
            downloadFile(perfId, file) {

                let url = Api.interestedPartiesUserFile + '/file/' + file.id;
                this.$http.get(url, {
                    responseType: 'blob'      //告诉服务器我们需要的响应格式
                }).then((res) => {
                    console.log(res)
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
                    });
                    aLink.href = URL.createObjectURL(blob)
                    aLink.download = file.fileName //标题
                    aLink.click()
                    document.body.appendChild(aLink)
                })
            },
            danxuan(row, index) {
                this.showdata.contractorId = row.contractorId
                this.showdata.contractorName = row.contractorName
                this.model2 = false

            },
            query() {
                let url = Api.getAdtProgramme;
                let id = this.taskInfo.workId;

                this.$http.get(url + '/' + id, {params: {}}).then((res) => {
                    this.showdata = res.data.data;

                    let url = Api.interestedPartiesUserFile+'/'+id+'/files/adtProgramme';
                    this.$http.get(url).then((res1) => {
                        this.uploadList = res1.data.data
                    }).catch(e => {
                        this.$Message.error("数据获取失败")
                    });
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            pageSizeChange1(pageSize) {
                this.pageModel2.pageSize = pageSize;
                this.query();
            },
            submitAndUpdate(){

                this.$refs['showdata'].validate((valid) => {
                    if (valid) {
                        this.buttonloading1 = true;
                        let data = {};
                        data = {
                            createUserId: this.user.userId,
                            userName: this.user.userName,
                            opinion: this.showdata.opinion,
                            taskId: this.taskInfo.taskId,
                            procinstId: this.taskInfo.procinstId,
                        };

                        let url = Api.updateAdtProgramme;
                        this.showdata.updateUserId = this.user.userId
                        this.showdata.updateOrgId = this.user.orgInfo.orgId
                        this.$http.post(url, this.showdata).then((res) => {
                            if (res.data.status == '200') {
                                data.route = '1';
                                this.$http.get(Api.taskComplete, {params: data}).then((res) => {
                                    this.buttonloading1 = false;
                                    if (res.data.status == '200') {
                                        this.$Message.success("审批成功")
                                        this.returnTo();
                                    } else {
                                        this.$Message.success("审批失败")
                                    }
                                }).catch(e => {
                                    this.$Message.error("数据获取失败")
                                })
                            }else {
                                this.buttonloading1 = false;
                            }
                        }).catch(e => {
                            this.$Message.error('请求失败');
                            this.buttonloading1 = false;

                        })
                    }
                })
            },
            submit() {
                this.$refs['showdata'].validate((valid) => {
                    if(valid) {
                        this.buttonloading1 = true;
                        let data = {};
                        data = {
                            createUserId : this.user.userId,
                            userName : this.user.userName,
                            opinion : this.showdata.opinion,
                            taskId : this.taskInfo.taskId,
                            procinstId : this.taskInfo.procinstId,
                            route : this.showdata.route
                        };
                        this.$http.get(Api.taskComplete, {params: data}).then((res) => {
                            this.buttonloading1 = false;
                            if(res.data.status=='200'){
                                this.$Message.success("审批成功")
                                this.returnTo();
                            }else{
                                this.$Message.success("审批失败")
                            }
                        }).catch(e => {
                            this.buttonloading1 = false;
                            this.$Message.error("数据获取失败")
                        })


                    } else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            pageChange1(pageNum) {
                this.pageModel2.currentPage = pageNum;
                this.query();
            },
            selectContractor() {
                this.model2 = true
                this.contractor = []
                let data = {
                    startPage: this.pageModel2.currentPage,
                    size: this.pageModel2.pageSize,
                    contractorName: this.pageModel2.contractorName
                }
                data = Object.assign(data);
                let url = Api.interestedPartiesAccountList
                this.$http.get(url, {params: data}).then((res) => {
                    console.log(res.data);
                    this.contractor = res.data.data.data;
                    this.pageModel2.total = res.data.data.totalSize;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            handleCancel() {
                this.showdata = {};
                this.$router.back();
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
        },
    }
</script>
<style lang='css' scoped>
    @import '../../../index.css';

</style>
